//
//  GGFilterHandler.m
//  视频录制实时切换滤镜
//
//  Created by 聚点互动iOS on 2020/12/28.
//

#import "GGFilterHandler.h"

@interface GGFilterHandler ()

/// 1⃣️裁剪滤镜 链条中的第一个滤镜
@property (nonatomic, weak) GPUImageCropFilter *cropFilter;

/// 2⃣️滤镜（包含裁剪滤镜）
@property (nonatomic, strong) NSMutableArray<GPUImageFilter *> *filters;

/// 第一个滤镜
@property (nonatomic, strong) GPUImageFilter *firstFilter;

/// 最后一个滤镜
@property (nonatomic, strong) GPUImageFilter *lastFilter;

@end

@implementation GGFilterHandler

- (instancetype)init{
    if (self = [super init]) {
        [self commonInit];
    }
    return self;
}
- (void)commonInit{
    /// 添加第一个滤镜(裁剪滤镜)
    [self addCropFilter];
    
}
- (void)setSource:(GPUImageOutput *)source{
    [source addTarget:self.firstFilter];
}

/// 添加裁剪滤镜
- (void)addCropFilter{
    GPUImageCropFilter *cropFilter = [GPUImageCropFilter new];
    cropFilter.cropRegion = CGRectMake(0, 0, 1, 1);
    [self addFilter:cropFilter];
    self.cropFilter = cropFilter;
}


/// 设置效果滤镜(添加输出)
- (void)setEffectFilter:(GPUImageFilter *)filter{
    [self addFilter:filter];
}

/// 替换掉最后一个滤镜
- (void)replaceLastFilter:(GPUImageFilter *)targetFilter{
    
    if (self.filters.count >= 2) {
        [self removeLastFilter];
        [self addFilter:targetFilter];
    }else{
        NSLog(@"目前只有一个裁剪滤镜，请添加效果滤镜后再替换！");
    }
}
- (void)removeLastFilter{
    if (self.filters.count == 1) {
        
    }else{
        /// 移除最后一个滤镜的所有输出
        NSArray *targets = self.filters.lastObject.targets;
        [self.filters.lastObject removeAllTargets];
        [self.filters removeLastObject];
        
        [self.lastFilter removeAllTargets];
        /// 添加滤镜后，重新添加所有的输出
        for (id <GPUImageInput> input in targets) {
            [self.filters.lastObject addTarget:input];
        }
    }
}


/// 添加滤镜
/// @param filter 滤镜
- (void)addFilter:(GPUImageFilter *)filter {
    /// 移除最后一个滤镜的所有输出
    NSArray *targets = self.filters.lastObject.targets;
    [self.filters.lastObject removeAllTargets];
    [self.filters.lastObject addTarget:filter];
    [self.filters addObject:filter];
    
    /// 添加滤镜后，重新添加所有的输出
    for (id <GPUImageInput> input in targets) {
        [self.filters.lastObject addTarget:input];
    }
}

- (NSMutableArray<GPUImageFilter *> *)filters{
    if (!_filters) {
        _filters = [NSMutableArray array];
    }
    return _filters;
}

- (GPUImageFilter *)firstFilter {
    return self.filters.firstObject;
}

- (GPUImageFilter *)lastFilter {
    return self.filters.lastObject;
}

@end
